<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;

class ArgumentsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        Log::debug('method:'.$request->method());
        Log::debug('url:'.$request->url());
        Log::debug('params:'.json_encode( $request->all()));

        if(!config('maqu.APP_DEBUG',false)){

            //check paramters

            $timestamp = Request::input('timestamp');
            $token = Request::input('token');
            $access_token = Request::input('access_token');

            if(empty($timestamp) || empty($token)){
                return response()->json(array(
                    'status' => RESPONSE_ARGUMENT_INVALID,
                    'code'=>'',
                    'message' => '非法参数',
                    'auth_failure' => AUTH_FAILURE_NO,
                    'data' => []
                ), 200);
            }

            //check timestamp   must
            $result = $this->check_timestamp($timestamp);
            if($result!==true){
                return $result;
            }

            //check token       must
            $result = $this->check_token($token,$access_token);
            if($result!==true){
                return $result;
            }
            //check device_sn    option
        }

        return $next($request);
    }

    private function check_timestamp($timestamp){

        $ctime =0;
        $stime = gmtime();

        $ctime =$timestamp;

        Log::debug('check_timestamp $timestamp:'.$ctime.' $stime:'.$stime);
        if(($ctime + 5*60)< $stime){
            return response()->json(array(
                'status' => RESPONSE_FAILURE,
                'code'=>'',
                'message' => 'timestamp超时',
                'auth_failure' => AUTH_FAILURE_NO,
                'data' => []
            ), 200);
        }
        unset($ctime);
        unset($stime);

        return true;
    }

    private function check_token($token,$access_token){

        /* 如果有POST的数据，则认为POST的数据是通知内容 */
//        $params = array();
//
//        if (!empty($_POST))
//        {
//            $params = $_POST;
//        }
//
//        /* 否则就认为是GET的 */
//        $params = $_GET;
//
//        $auth_token = $params['token'];
        $params =Request::all();

        /* 去除不参与签名的数据 */
        unset($params['token']);

        /* 排序 */
        ksort($params);
        reset($params);

        $sign  = '';
        $tempstr = '';
        foreach ($params AS $key => $value)
        {
            if(is_array($value)){
                if(count($value)==1){
                    //此处为了与前台对应
                    $tempstr .=$value[0];
                } else {
                    foreach($value AS $v){
                        $tempstr .=$v . ',';
                    }
                }

                $sign  .= "{$key}={$tempstr}&";
            } else {
                $sign  .= "{$key}={$value}&";
            }

        }

        $sign = substr($sign, 0, -1);
        Log::debug('$sign str:'.$sign);

        $sign = rawurlencode($sign);//为了对应中文md5前后台不统一问题  urlencode把空格转化为+ ,与前台encodeURIComponent不匹配
        Log::debug('request:'.Request::url());
        Log::debug('urlencode:'.$sign);

        if($access_token){
            $encrypt_string = think_ucenter_md5($sign,$access_token.config('app.key'));
        } else {
            $encrypt_string = think_ucenter_md5($sign,config('app.key'));
        }

        Log::debug('check_token $token:'.$token.' $encrypt_string:'.$encrypt_string);
        if($encrypt_string != $token){
            Log::debug('验签失败');
            return response()->json(array(
                'status' => RESPONSE_FAILURE,
                'code'=>'',
                'message' => '验签失败',
                'auth_failure' => AUTH_FAILURE_NO,
                'data' => $sign
            ), 200);
        }
        Log::debug('验签success');
        return true;

    }
}
